﻿using System.Diagnostics;
using System.Threading.Tasks;
using Windows.Media;
using Windows.Storage;
using Windows.UI.Input;
using Windows.UI.Popups;
using AudioBooks.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Hub Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=321224
using AudioBooks.Controls;
using AudioBooks.Data;
using AudioBooks.SQLite;
using AudioBooks.ViewModel;
using Books.SQLite;
using Services.Model;
using SQLite;

namespace AudioBooks.BookDetailsGroup
{
    /// <summary>
    /// A page that displays a grouped collection of items.
    /// </summary>
    public sealed partial class ItemPage : Page
    {
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();
        private GetBookDetail getBookDetail;
     
        /// <summary>
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        private PlayerViewModel PlayerViewModel = new PlayerViewModel();
        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and 
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        public ItemPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Required;
            this.DefaultViewModel["Player"] = this.PlayerViewModel;

        }








        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
            systemMediaControls.ButtonPressed += SystemMediaControls_ButtonPressed;
            systemMediaControls.IsPlayEnabled = true;
            systemMediaControls.IsPauseEnabled = true;
            systemMediaControls.IsStopEnabled = true;
        }

        #region NavigationHelper registration

        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// 
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
            this.Loading.Visibility = Visibility.Visible;
            string getbookId;
            PlayChapterInfo item;
            try
            {
                item = (PlayChapterInfo)e.Parameter;
            }
            catch (Exception)
            {
                item = null;
            }
           
            if (item != null)
            {
                getbookId = item.BookId;
                await loadData(getbookId);
                await PlayChapter(item.ChapterName);
                await Task.Delay(500);
                hub.ScrollToSection(nowPlayingHub);
                App.Player.Position = item.Position;
            }
            else
            {
                getbookId = (string)e.Parameter;
                await loadData(getbookId);
            }






            this.Loading.Visibility = Visibility.Collapsed;
        }

        private async Task loadData(string bookID)
        {
            App.BookIdSelect = bookID;

            if (App.Player.PlayToSource == null)
            {

                addbookmarkappbarbutton.Visibility = Visibility.Collapsed;
                nowPlayingHub.Visibility = Visibility.Collapsed;
            }

            var a = FindChildControl<GridView>(this, "bookChapterListView") as GridView;
            a = new GridView();

            getBookDetail = await App.CallService.GetBookDetailAsync(bookID, string.Empty);



            if (getBookDetail != null && getBookDetail.book_detail != null)
            {
                if (getBookDetail.chapter_list.Count > 0)
                {
                    var listData = ManagerFilesDownloadComplete.GetDataDownLoadFiles();
                    if (listData != null)
                    {
                        foreach (var m in getBookDetail.chapter_list)
                        {

                            var getUrl = (new Uri(m.audio_link)).Segments; ;
                            var checkFilesExits = listData.FirstOrDefault(k => k.FileName == getUrl[getUrl.Length - 1] &&
                                k.BookId == App.BookIdSelect);
                            if (checkFilesExits != null)
                                m.isDownload = true;

                        }
                    }

                }


            }
            this.DefaultViewModel["Group"] = getBookDetail.book_detail;
            this.DefaultViewModel["Items"] = getBookDetail.chapter_list;
            this.DefaultViewModel["Title"] = getBookDetail.book_detail.book_name;
            var bookmark = HandlePlayChapter.GetDataPlayChapterInfosByBookId(bookID);
            if (bookmark == null || bookmark.Count == 0)
            {
                bookmarkHub.Visibility = Visibility.Collapsed;
            }
            else
            {
                bookmarkHub.Visibility = Visibility.Visible;
                this.DefaultViewModel["Bookmarks"] = bookmark;
            }

        }

        private async void SystemMediaControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs e)
        {
            switch (e.Button)
            {
                case SystemMediaTransportControlsButton.Play:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        App.Player.Play();
                    });
                    break;

                case SystemMediaTransportControlsButton.Pause:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        App.Player.Pause();
                    });
                    break;

                case SystemMediaTransportControlsButton.Stop:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        App.Player.Stop();
                    });
                    break;

                default:
                    break;
            }
        }


        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        #endregion

        private async void selectItemChapter(object sender, ItemClickEventArgs e)
        {
            var itemSelect = e.ClickedItem as ChapterList;
            if (itemSelect.IsDownload)
            {
                var checkExitsFileDownloadComplete = ManagerFilesDownloadComplete.CheckExitsFolder(App.BookIdSelect);
                if (checkExitsFileDownloadComplete)
                {
                    await PlayChapter(itemSelect.chapter_no);
                }
            }
            else
            {
                var items = ((GridView)sender).ContainerFromItem(itemSelect) as GridViewItem;
                var getControl = items.ContentTemplateRoot as DownloadChapter;
                var listChapter = new List<ChapterList>();
                listChapter.Add(itemSelect);
                getControl.DownloadAll.Execute(listChapter);
            }
        }

        SystemMediaTransportControls systemMediaControls;
        private async Task AddControl(StorageFile getItem)
        {
            nowPlayingHub.Visibility = Visibility.Visible;
            addbookmarkappbarbutton.Visibility = Visibility.Visible;
            PlayerViewModel.ChapterId = App.NowPlayChapterId = getItem.DisplayName.Replace(".mp3", "");

            await SetMediaElementSourceAsync(getItem);

            if (getItem != null)
            {
                MediaPlaybackType mediaPlaybackType = MediaPlaybackType.Music;
                // Inform the system transport controls of the media information
                if (!(await systemMediaControls.DisplayUpdater.CopyFromFileAsync(mediaPlaybackType, getItem)))
                {
                    //  Problem extracting metadata- just clear everything
                    systemMediaControls.DisplayUpdater.ClearAll();
                }
                systemMediaControls.DisplayUpdater.Update();
            }

        }

        private async Task SetMediaElementSourceAsync(StorageFile getItem)
        {
            var stream = await getItem.OpenAsync(Windows.Storage.FileAccessMode.Read);
            App.Player.SetSource(stream, getItem.ContentType);
        }

        private DependencyObject FindChildControl<T>(DependencyObject control, string ctrlName)
        {
            int childNumber = VisualTreeHelper.GetChildrenCount(control);
            for (int i = 0; i < childNumber; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(control, i);
                FrameworkElement fe = child as FrameworkElement;
                // Not a framework element or is null
                if (fe == null) return null;

                if (child is T && fe.Name == ctrlName)
                {
                    // Found the control so return
                    return child;
                }
                else
                {
                    // Not found it - search children
                    DependencyObject nextLevel = FindChildControl<T>(child, ctrlName);
                    if (nextLevel != null)
                        return nextLevel;
                }
            }
            return null;
        }
        private void Player_AddControl(StorageFile eFile)
        {
            AddControl(eFile);
        }

        private async void GridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var bookmark = (PlayChapterInfo)e.ClickedItem;
            if (!(bookmark.ChapterName == App.NowPlayChapterId && bookmark.BookId == App.NowPlayBookId))
            {
                await PlayChapter(bookmark.ChapterName);
                await Task.Delay(500);
            }
            hub.ScrollToSection(nowPlayingHub);
            App.Player.Position = bookmark.Position;
        }



        private async Task PlayChapter(string chapterID)
        {
            var getFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(App.BookIdSelect);

            var getListFile = await getFolder.GetFilesAsync();
            App.GlobalPlaylist = getListFile.ToList();

            if (getListFile.Count > 0)
            {
                try
                {
                    for (int i = 0; i < getListFile.Count; i++)
                    {
                        if (int.Parse(getListFile[i].DisplayName.Replace(".mp3", "")) == int.Parse(chapterID))
                        {
                            App.PlayIndex = i;
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    return;
                }

                try
                {
                    App.GlobalPlaylist = getListFile;
                    var getItem = App.GlobalPlaylist[App.PlayIndex];

                    App.NowPlayBookId = getBookDetail.book_detail.book_id;
                    PlayerViewModel.BookName = App.NowPlayTitle = getBookDetail.book_detail.book_name;
                    PlayerViewModel.ImageLink = App.ImageLink =getBookDetail.book_detail.cover_link;


                    await AddControl(getItem);
                }
                catch (Exception ex)
                {
                    return;
                }
            }
        }

        private async void Player_AddBookMark(object sender, EventArgs e)
        {
            var bookmark = HandlePlayChapter.GetDataPlayChapterInfosByBookId(App.BookIdSelect);
            if (bookmark == null || bookmark.Count == 0)
            {
                bookmarkHub.Visibility = Visibility.Collapsed;
            }
            else
            {
                bookmarkHub.Visibility = Visibility.Visible;
                this.DefaultViewModel["Bookmarks"] = bookmark.OrderByDescending(m => m.KeyMark).ToList();
                bookmarkMessage.Visibility = Visibility.Visible;
                await Task.Delay(1500);
                bookmarkMessage.Visibility = Visibility.Collapsed;
            }
            
        }

        private void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            var listChapter = this.DefaultViewModel["Items"] as List<ChapterList>;
            if (listChapter.Count > 0)
            {
                foreach (var chapter in listChapter)
                {
                    if (!chapter.IsDownload)
                    {
                        var a = FindChildControl<GridView>(this, "bookChapterListView") as GridView;
                        var items = a.ContainerFromItem(chapter) as GridViewItem;
                        var getControl = items.ContentTemplateRoot as DownloadChapter;
                        var listChapterData = new List<ChapterList>();
                        listChapterData.Add(chapter);
                        getControl.DownloadAll.Execute(listChapterData);
                    }

                }
            }
        }

        private async void AppBarButton_Click_1(object sender, RoutedEventArgs e)
        {
            var BookMark = new PlayChapterInfo()
            {
                BookId = App.NowPlayBookId,
                Position = App.Player.Position,
                ChapterName = App.NowPlayChapterId,
                ImagePath = ((PlayerViewModel)this.DefaultViewModel["Player"]).ImageLink,
                BookName = App.NowPlayTitle
            };
            if (string.IsNullOrEmpty(BookMark.BookId) || string.IsNullOrEmpty(BookMark.ChapterName))
            {
                MessageDialog message = new MessageDialog("Please choose chapter before.");
                await message.ShowAsync();
                return;
            }
            HandlePlayChapter.SaveDataPlayChapterInfo(BookMark);
            Player_AddBookMark(sender, new EventArgs());
        }

        private void AppBarButton_Click_2(object sender, RoutedEventArgs e)
        {
            HandleBookmark.DeleteAllBookMark(App.BookIdSelect);
            bookmarkHub.Visibility = Visibility.Collapsed;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var button = (Button) sender;
            var data = (PlayChapterInfo)button.DataContext;
            HandleBookmark.DeleteBookMark(data.KeyMark);
            message.Text = "Bookmark deleted";
            Player_AddBookMark(sender, new EventArgs());
            message.Text = "Add bookmarks success";
        }

        private async void AppBarButton_Click_3(object sender, RoutedEventArgs e)
        {
            await HandleBookmark.DeleteBook(App.BookIdSelect);            
            await loadData(App.BookIdSelect);
            HandleBookmark.DeleteAllBookMark(App.BookIdSelect);
            bookmarkHub.Visibility = Visibility.Collapsed;
        }


      
    }
}
